

clear

***set working directory to main replication directory
use "data/anes_timeseries_cdf_stata_20220916.dta"

gen year = VCF0004

*** Party ID Items

gen pid7 = VCF0301
replace pid7 = . if pid7==0

gen strongrep = 0 if pid7!=.
replace strongrep = 1 if pid7==7

gen rep_id = 0 if pid7!=.
replace rep_id = 1 if pid7>=6 & pid7!=.

gen leanrep_id = 0 if pid7!=.
replace leanrep_id = 1 if pid7>=5 & pid7!=.

gen strongdem = 0 if pid7!=.
replace strongdem = 1 if pid7==1 & pid7!=.

gen dem_id = 0 if pid7!=.
replace dem_id = 1 if pid7>=1 & pid7<=2

gen leandem_id = 0 if pid7!=.
replace leandem_id = 1 if pid7>=1 & pid7<=3

gen pid3 = 0 if VCF0301<=2
replace pid3 = 1 if VCF0301>=3 & VCF0301<=5
replace pid3 = 2 if VCF0301>=6 & VCF0301<=7

gen lean3 = 0 if VCF0301==3
replace lean3 = 1 if VCF0301==4
replace lean3 = 2 if VCF0301==5

gen partyid_base = 0 if pid3==0
replace partyid_base = 0 if lean3==0
replace partyid_base = 1 if lean3==1
replace partyid_base = 2 if lean3==2
replace partyid_base = 2 if pid3==2

gen strongpartisan = 1 if pid7!=.
replace strongpartisan = 0 if pid7==1
replace strongpartisan = 2 if pid7==7

gen partystrength = 0 if pid7!=.
replace partystrength = 1 if pid7==1
replace partystrength = 1 if pid7==7

gen pureindependent = 0 if pid7!=.
replace pureindependent = 1 if pid7==4

gen partyid_pre=partyid_base if year<2000
gen partyid_post= partyid_base if year>1998

** Thermometer Items

gen reptherm = VCF0224
replace reptherm = VCF0202 if year<=1976
replace reptherm = . if reptherm==98
replace reptherm = . if reptherm==99

gen demtherm = VCF0218
replace demtherm = VCF0201 if year<=1976
replace demtherm = . if demtherm==98
replace demtherm = . if demtherm==99

gen thermdiff = demtherm-reptherm


*** Votes

gen partyvotepres3 = 0 if VCF0706==1
replace partyvotepres3 = 2 if VCF0706==2
replace partyvotepres3 = 1 if VCF0706==3
replace partyvotepres3 = 1 if VCF0706==4

gen partythermdiff = thermdiff if partyid_base==0
replace partythermdiff = -thermdiff if partyid_base==2

gen partyloyalty = 0 if partyid_base!=1 & partyid_base!=. & partyvotepres3!=.
replace partyloyalty = 1 if partyid_base==0 & partyvotepres3==0
replace partyloyalty = 1 if partyid_base==2 & partyvotepres3==2

collapse (mean) partythermdiff partyloyalty pureindependent partystrength [iw=VCF0009z], by(year)
drop if year==2002
saveold "data/affective_polarization.dta", version(12) replace

*** Now load voteswitcher data
clear
insheet using "data/typesofvoters_anes.csv", comma
gen modifiedmp = floating/(1-nonvoter-decliner)
gen modifiedall = (totalchange)/(1-nonvoter-decliner)
keep year modifiedmp modifiedall
merge 1:1 year using  "data/affective_polarization.dta"
sort year
drop _merge
saveold "data/affective_polarization_fig1.dta", version(12) replace
